package com.lj.mp.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lj.mp.constant.MpConstant;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author luojing
 * @since 2024/10/25 18:04
 * mp自动填充处理器
 */
public class MyBatisPlusFillHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        this.fillStrategy(metaObject, MpConstant.CREATE_TIME, now);
        this.fillStrategy(metaObject, MpConstant.UPDATE_TIME, now);
        this.fillStrategy(metaObject, MpConstant.VERSION, 0);
        this.fillStrategy(metaObject, MpConstant.DELETED, false);
        Long userId = getUserId();
        this.fillStrategy(metaObject, MpConstant.CREATE_USER, userId);
        this.fillStrategy(metaObject, MpConstant.UPDATE_USER, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(MpConstant.UPDATE_TIME, LocalDateTime.now(), metaObject);
        this.setFieldValByName(MpConstant.UPDATE_USER, getUserId(), metaObject);
    }

    /**
     * 获取用户id
     */
    private Long getUserId() {
        try {
            return StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            return -1L;
        }
    }
}
